package com.bootdo.contract.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bootdo.contract.config.MyHttpServletRequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;


@Configuration
public class AppLoginInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(AppLoginInterceptor.class);
	
	@Autowired
	private UserService userService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		log.info("Get in interceptor preHandle.");
        JSONObject responseJson = new JSONObject();
        try {
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            String requestMethord = request.getRequestURI();//请求方法
            if (requestMethord == null) {
                return false;
            }
 
            // 获取Content-Type=application/json 请求参数
            JSONObject parameterMap = JSON.parseObject(new MyHttpServletRequestWrapper(request).getBodyString(request));
            log.info("请求参数" + parameterMap);
            
            String token = parameterMap.getString("token");
            log.info(token);
            if (token!=null && !token.equals("")) {
				UserDO userDo = new UserDO();
				userDo.setToken(token);
				UserDO user = userService.getUserByUserInfo(userDo);
				if (user!=null) {
					request.setAttribute("user", user);
					return true;
				}else {
					responseJson.put("code", "10");
		            responseJson.put("msg", "Token已过期");
		            ajaxResponseJsonReturn(response, request, responseJson);
					return false;
				}
			}/*else {
                responseJson.put("code", "11");
                responseJson.put("msg", "请登录");
                ajaxResponseJsonReturn(response, request, responseJson);
                return false;
            }*/
 
        } catch (Exception e) {
            e.printStackTrace();
            responseJson.put("code", "-1");
            responseJson.put("msg", "接口调用异常");
            ajaxResponseJsonReturn(response, request, responseJson);
            return false;
        }
        log.info("验签通过。");
        return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}
	
    protected void ajaxResponseJsonReturn(HttpServletResponse response, HttpServletRequest request, JSONObject responseJson) throws IOException {
        response.setCharacterEncoding("UTF-8");//Constant.ENCODE_UTF8
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(responseJson.toJSONString());
        out.flush();
        out.close();
    }


}
